package com.rdc.qingkou.view.fragment;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.Toast;

import com.rdc.qingkou.R;

import java.io.IOException;


public class BaseMediaPlayerFragment extends Fragment implements MediaPlayer.OnPreparedListener, View.OnClickListener {

    protected MediaPlayer mediaPlayer = null;
    private boolean isPrepared = false;//音频是否准备好
    protected String voiceUrl;


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!isVisibleToUser) {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            }
        }
    }

    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        mediaPlayer.start();
        isPrepared = true;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_card_voice_imageView:
                if (mediaPlayer == null) {
                    Toast.makeText(getActivity(), "音频加载中", Toast.LENGTH_SHORT).show();
                    mediaPlayer = new MediaPlayer();
                    try {
                        mediaPlayer.setDataSource(voiceUrl);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mediaPlayer.prepareAsync();
                    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    mediaPlayer.setOnPreparedListener(this);
                } else if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                } else if (isPrepared) {
                    mediaPlayer.start();
                }
                break;
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}
